//
//  InviteViewModel.swift
//  xiaoqiao
//
//  Created by 冷子豪 on 2017/8/12.
//  Copyright © 2017年 冷子豪. All rights reserved.
//

import Foundation

var inviteViewModel = InviteViewModel()

class InviteViewModel{
    /// 根据用户id 查询上线的userid
    ///
    /// - Parameter userid: 当前用户id
    /// - Returns: 上线id
    func getUpGradeByUserId(userid:Int) -> Int{
        var upId = 0
        // 同步Get方式
        // 1.创建URL对象
        let url:URL! = URL(string:"\(info.API_URL)/xqjr/ascription/getUpGradeByUserId?userid=\(userid)")
        
        // 2.创建Request对象
        let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        
        // 3.响应对象
        var response:URLResponse?
        
        // 4.发出请求
        do {
            // Data,json数据
            let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)
            // 返回id
            let dic = NSString(data:received,encoding:String.Encoding.utf8.rawValue)! as String
            upId = Int(dic)!
//            let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments)
            
        } catch let error{
            print(error.localizedDescription)
        }
        return upId
    }
    
    /// 根据用户id 查询下线的user队列
    ///
    /// - Parameter userid: 当前用户id
    /// - Returns: user队列
    func getDownGradeByUserId(userid:Int) -> [User]{
        
        // 同步Get方式
        var arrayM = [User]()
        // 1.创建URL对象
        let url:URL! = URL(string:"\(info.API_URL)/xqjr/ascription/getDownGradeByUserId?userid=\(userid)")
        print("\(info.API_URL)/xqjr/ascription/getDownGradeByUserId?userid=\(userid)")
        // 2.创建Request对象
        let urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
        
        // 3.响应对象
        var response:URLResponse?
        
        // 4.发出请求
        do {
            // Data,json数据
            let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)
            // 字典数据
            let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments) as! Array<[String:Any]>
            print(dic)
            
            for item in dic {
                let h = User(dic: item)
                
                arrayM.append(h)
            }
            
        } catch let error{
            print(error.localizedDescription);
        }
        return arrayM
    }
}
